package com.leff.cards.data;

import java.util.ArrayList;
import java.util.Arrays;

import org.json.simple.JSONArray;

import android.util.Log;

import com.leff.cards.util.Secrets;
import com.leff.cards.util.Dictionary;
import com.leff.cards.web.QueryDispatcher;
import com.leff.cards.web.requests.InviteRequest;

public class Contacts implements Secrets {

	private static Contacts instance;
	public static Contacts get() {
		return instance;
	}
	
	private User[] mUsers;
	private CharSequence[] mNames;
	private boolean[] mSelections;
	
	private int mNumSelected = 0;
	
	private Contacts() {
	}
	
	public CharSequence[] getFriendNames() {
		return mNames;
	}
	public boolean[] getSelections() {
		return mSelections;
	}
	public void setSelection(int index, boolean selected) {
		mSelections[index] = selected;
		
		if(selected) {
			mNumSelected++;
		} else {
			mNumSelected--;
		}
		Log.v(TAG, mNames[index] + (selected ? " Selected" : " Unselected"));
	}
	
	public ArrayList<Long> getSelectedFbIds() {
		
		ArrayList<Long> ids = new ArrayList<Long>();
		for(int i = 0; i < mSelections.length; i++) {
			if(!mSelections[i]) {
				continue;
			}
			ids.add(mUsers[i].fbid);
		}
		return ids;
	}
	
	public void dispatchInvitations(long groupId) {
		
		if(mNumSelected < 1) {
			return;
		}
		
		long[] ids = new long[mNumSelected];
		int index = 0;
		for(int i = 0; i < mSelections.length; i++) {
			if(!mSelections[i]) {
				continue;
			}
			ids[index] = mUsers[i].fbid;
			index++;
		}
		
		new QueryDispatcher(new InviteRequest(groupId, ids)).execute();
			
		mSelections = new boolean[mNames.length];
		mNumSelected = 0;
	}
	
	public static void initFromFacebookData(Dictionary dict) {
		
		instance = new Contacts();
		
		ArrayList<User> users = new ArrayList<User>();
		ArrayList<CharSequence> names = new ArrayList<CharSequence>();
		
		JSONArray arr = (JSONArray)dict.get("data");
		if(arr == null) {
			return;
		}
		for(Object O : arr) {
			Dictionary data = Dictionary.fromJSONObject(O);
			
			String idStr = (String)data.get("id");
			long id = Long.parseLong(idStr);
			String name = (String)data.get("name");
			
			User U = new User(id, name);
			
			users.add(U);
			names.add(U.displayName);
		}

		instance.mUsers = new User[users.size()];
		users.toArray(instance.mUsers);
		Arrays.sort(instance.mUsers);
		
		instance.mNames = new CharSequence[names.size()];
		names.toArray(instance.mNames);
		Arrays.sort(instance.mNames);
		
		instance.mSelections = new boolean[names.size()];
	}
}
